package com.coffee.web;


import com.coffee.core.CoffeeException;
import com.coffee.core.CoffeeResponse;
import com.coffee.core.CoffeeResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;

/**
 * @author: songkui
 * @version: 1.0
 * @date: 2019/5/25 12:40
 * @apiNote: 统一返回异常数据格式
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class CoffeeGlobalExceptionHandler {

    //运行时异常
    @ExceptionHandler(CoffeeException.class)
    public CoffeeResponse<?> runtimeExceptionHandler(CoffeeException ex) {
        log.error("CoffeeException: {}", ex.getMessage());
        return CoffeeResponse.response(ex.getState());
    }

    /**
     * 校验错误拦截处理
     *
     * @param exception 错误信息集合
     * @return 错误信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CoffeeResponse<String> validationBodyException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            ObjectError e = errors.get(0);
            FieldError fieldError = (FieldError) e;
            log.error("MethodArgumentNotValidException:  object{},field{},errorMessage{}}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
            return CoffeeResponse.response(fieldError.getDefaultMessage(), CoffeeResponseEnum.ParamInvalid);
        }
        log.error("MethodArgumentNotValidException:  ParamInvalid, message: {}", Optional.of(exception.getMessage()).orElse(""));
        return CoffeeResponse.response(CoffeeResponseEnum.ParamInvalid);
    }

    @ExceptionHandler({Exception.class})
    public CoffeeResponse<?> exception(Exception ex) {
        log.error("Exception: ", ex);
        return CoffeeResponse.response(CoffeeResponseEnum.SysException);
    }



}
